﻿#include "QtWidgetsApplication3.h"

// 1、打开服务器
void QtWidgetsApplication3::open_connect_server()
{
	// 创建服务器
	tcpserver = new QTcpServer(this);

	// 当有新的客户端连接时，newConnection信号被触发
	connect(tcpserver, &QTcpServer::newConnection, this, &QtWidgetsApplication3::new_connect);

	// 监听指定IP+端口
	if (tcpserver->listen(QHostAddress((ui.comboBox->currentText())), ui.lineEdit_port->text().toUShort()))
	{
		QString message = QString("正在监听：%1-%2").arg(ui.comboBox->currentText()).arg(ui.lineEdit_port->text());
		ui.textEdit->append(message);
		ui.open_server->setEnabled(false);
		ui.close_server->setEnabled(true);
	}
}

// 2、客户端新连接
void QtWidgetsApplication3::new_connect()
{
	tcpsocket = tcpserver->nextPendingConnection();     //获取客户端套接字
	QThread* thread = new QThread();                    //创建线程
	ClientThread* client = new ClientThread(tcpsocket); //创建对象
	client->moveToThread(thread);                       //将客户端移动到线程中
	thread->start();                                    //启动线程

	//开启线程,在run中将线程号、客户端IP+端口、Socket套接字发送给UI更新
	connect(thread, &QThread::started, client, &ClientThread::run);

	//更新列表和模型,发送数据更新UI
	connect(client, &ClientThread::send_socket_info, this, &QtWidgetsApplication3::socket_info);

	//客户端主动离线
	connect(client, &ClientThread::send_socket_on_disconnect, this, &QtWidgetsApplication3::socket_on_disconnect);

	//客户端数据接收
	connect(client, &ClientThread::send_socket_readAll, this, &QtWidgetsApplication3::socket_readAll);
}

// 3、关闭服务器
void QtWidgetsApplication3::close_server()
{
	tcpserver->deleteLater();           // 稍后删除自己
	tcpserver->close();                 // 关闭服务器

	// 1. 清理所有线程和Socket连接
	for (auto thread : threadMap.keys()) {
		QTcpSocket* socket = threadMap[thread];
		if (socket) {
			socket->abort(); // 断开连接
			socket->deleteLater(); // 释放Socket资源
		}

		if (thread) {
			thread->quit(); // 退出线程
			thread->wait(); // 等待线程结束
			thread->deleteLater(); // 释放线程资源
		}
	}

	// 2. 清空映射表
	threadMap.clear();

	// 3. 清空ListView的数据模型
	if (ItemModel) {
		ItemModel->clear();
	}

	// 4. 在textEdit中显示服务器关闭信息
	ui.textEdit->append("服务器已关闭，所有连接已清理");
	ui.open_server->setEnabled(true); // 启用打开服务器按钮
	ui.close_server->setEnabled(false); // 禁用关闭服务器按钮
}

// 4、更新列表和模型
void QtWidgetsApplication3::socket_info(QThread* thread,QString info, QTcpSocket* tcpsocket)
{
	threadMap[thread] = tcpsocket; // 保存线程和IP
	QString threadStr = QString("IP: %1 - 线程: %2").arg(info).arg((quintptr)thread, 0, 16);
	QStandardItem* item = new QStandardItem(threadStr);
	
	item->setCheckable(true);         // 设置可勾选属性
	item->setCheckState(Qt::Checked); // 默认勾选
	ItemModel->appendRow(item);
    ui.listView->setModel(ItemModel); 
}

// 5、踢人
void QtWidgetsApplication3::kick_out()
{
	// 遍历所有项，检查哪些被选中
	for (int i = 0; i < ItemModel->rowCount(); ++i) {
		QStandardItem* item = ItemModel->item(i);
		if (item && item->checkState() == Qt::Checked) {
			// 解析线程ID
			QString threadStr = item->text();
			QString threadIdStr = threadStr.split("线程: ").last();
			bool ok;
			quintptr threadId = threadIdStr.toULongLong(&ok, 16);
			if (ok) {
				// 查找对应的线程和socket
				QThread* targetThread = nullptr;
				QTcpSocket* targetSocket = nullptr;

				for (auto thread : threadMap.keys()) {
					if ((quintptr)thread == threadId) {
						targetThread = thread;
						targetSocket = threadMap[thread];
						break;
					}
				}

				if (targetSocket) {
					targetSocket->abort(); // 立即关闭连接，丢弃所有待发送数据
					ui.textEdit->append(QString("已断开连接，线程ID: %1").arg(threadIdStr));
					
					// 清理线程
					if (targetThread) {
						targetThread->quit();
						targetThread->wait();
						targetThread->deleteLater(); //根据需要决定是否删除线程
					}

					// 从模型中移除该项
					ItemModel->removeRow(i);
					// 从映射中移除
					threadMap.remove(targetThread);
					i--; // 因为移除了一行，索引需要调整
				}
			}
		}
	}
}

// 6、客户端主动断开连接
void QtWidgetsApplication3::socket_on_disconnect(QThread* thread, QString info, QTcpSocket* tcpsocket)
{
	// 查找对应的线程
	QThread* targetThread = nullptr;
	for (auto thread : threadMap.keys()) {
		if (threadMap[thread] == tcpsocket) {
			targetThread = thread;
			break;
		}
	}

	if (targetThread) {
		// 从列表中查找并移除对应的项
		QString threadIdStr = QString("%1").arg((quintptr)targetThread, 0, 16);
		for (int i = 0; i < ItemModel->rowCount(); ++i) {
			QStandardItem* item = ItemModel->item(i);
			if (item && item->text().contains(threadIdStr)) {
				ItemModel->removeRow(i);
				break;
			}
		}

		// 清理线程
		targetThread->quit();
		targetThread->wait();
		targetThread->deleteLater();

		// 从映射表中移除
		threadMap.remove(targetThread);

		// 在textEdit中显示信息
		ui.textEdit->append(QString("客户端 %1 主动断开连接，线程ID: %2").arg(info).arg(threadIdStr));
	}
}

// 7、接收数据
void QtWidgetsApplication3::socket_readAll(QThread* thread, QString info, QTcpSocket* tcpsocket, QByteArray data)
{
	// 查找对应的客户端信息（IP和线程ID）
	QString threadIdStr;
	QThread* targetThread = nullptr;

	// 从映射表中查找线程
	for (auto thread : threadMap.keys()) {
		if (threadMap[thread] == tcpsocket) {
			targetThread = thread;
			threadIdStr = QString("%1").arg((quintptr)thread, 0, 16);
			break;
		}
	}

	// 显示接收信息到textEdit
	if (!info.isEmpty() && !threadIdStr.isEmpty()) {
		ui.textEdit->append(QString("[接收] 客户端 %1 (线程ID: %2): %3")
			.arg(info)
			.arg(threadIdStr)
			.arg(QString(data)));
	}
}

// 8、发送数据
void QtWidgetsApplication3::send_data()
{
	// 检查是否有客户端连接
	if (threadMap.isEmpty()) {
		ui.textEdit->append("[广播失败] 没有任何客户端连接");
		return;
	}

	QString sendData=ui.lineEdit->text();
	foreach(QTcpSocket * socket, threadMap.values()) {
		if (socket && socket->state() == QTcpSocket::ConnectedState) {
			socket->write(sendData.toUtf8());
			socket->flush(); //立即发送
		}
	}
	ui.textEdit->append(QString("[广播] 所有客户端"));
}

// 9、初始化
void  QtWidgetsApplication3::init()
{
	// 默认禁用关闭服务器按钮
	ui.close_server->setEnabled(false); 

	// 获取本机所有IP地址，更新到comboBox
	QList<QHostAddress> ipAddresses = QNetworkInterface::allAddresses();
	for (const QHostAddress& address : ipAddresses) {
		if (address.protocol() == QAbstractSocket::IPv4Protocol
			&& address != QHostAddress::LocalHost) {
			ui.comboBox->addItem(address.toString());
		}
	}
}

// 10、清除数据
void QtWidgetsApplication3::clear_data()
{
	ui.textEdit->clear();
}
